import React from "react";
import { connect } from "react-redux";
import "./index.scss";
import { withRouter } from 'react-router-dom'
import {Button, Space, Divider, Table, Spin, Avatar, Tag } from "antd";
import { CaretRightOutlined, PlusOutlined, FolderAddOutlined, HeartOutlined, VerticalAlignBottomOutlined } from "@ant-design/icons";
import {GetRecommendSong} from "../../api/Recommend/Recommend";
import { GetPlayListDetail } from "../../api/Playlist/playlist";
import { fitterYMRTime } from "../../util/timerfilter";
import { GetAudioDetail } from "../../api/buttonAudio/buttonAudio";
import emitter from "../../event";
import {SethistoryActive, SethistroyList} from "../../store/action";

const mapStateToProps = (state) => {
    return {
        state,
    };
}

const mapDispatchToProps = (dispatch) => {
    return {
        sethistory: (list) => dispatch(SethistroyList(list)),
        sethistoryactive: (id) => dispatch(SethistoryActive(id)),
    }
}

class PlayListPage extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            id: null,
            loading: true,
            recommendList: [],
            playlist: null,
        };
        this.PlayAll = this.PlayAll.bind(this);
    }

    componentDidMount() {
        this.getPlayList();
    }


    getPlayList(){
        let id = this.props.match.params.id;
        this.setState({
            id: id,
        })
        if(id === 'recommend'){
            GetRecommendSong().then(res => {
                const { code, data } = res;
                if(code == 200){
                    this.setState({
                        recommendList: data.dailySongs,
                        loading: false,
                    })
                }
            })
        }else {
            let form = {
                id,
            }
            GetPlayListDetail(form).then(res => {
                const { code,playlist } = res;
                if(code == 200){
                    let songids = [];
                    playlist.trackIds.forEach(r => {
                        songids.push(r.id);
                    })
                    this.setState({
                        playlist: playlist,
                        recommendList: playlist.tracks,
                        loading: false,
                    })
                    let detsongform = {
                        ids: songids.join(','),
                    }
                    GetAudioDetail(detsongform).then(result => {
                        const { code, songs } = result;
                        if(code == 200){
                            this.setState({
                                recommendList: songs
                            })
                        }
                    })
                }
            })
        }
    }

    PlayAll(){
        // 播放全部
        const { recommendList } = this.state;
        let historylist = [];
        recommendList.forEach(r => {
            historylist.push({
                id: r.id,
                MusicInfo: r,
                allTime: r.dt,
            })
        })

        this.props.sethistory(historylist);
        this.props.sethistoryactive(recommendList[0].id);

        emitter.emit('PlayAudio',recommendList[0].id,recommendList);
    }

    PlayTitle(){
        const { id, playlist } = this.state;
        if(id === 'recommend'){
            const day = new Date().getDate();
            let className = 'icon-rili'+day;
            return <div className="Recommend_box">
                <div className="n-daily">
                    <div className="NowTime">
                        <i className={'iconfont'+ ' ' +className}></i>
                    </div>
                    <div className="tips">
                        <span className="tips_title">每日歌曲推荐</span>
                        <span className="tips_tips">根据你的音乐口味生成，每天6:00更新</span>
                    </div>
                </div>
                <div className="PlayButton_box">
                    <Space>
                        <div className="Play_box">
                            <Button onClick={this.PlayAll} className="PlayAll" icon={<CaretRightOutlined />}>
                                播放全部
                            </Button>
                            <Button className="Add" icon={<PlusOutlined />}></Button>
                        </div>
                        <Button className="SCbut" icon={<FolderAddOutlined />}>
                            收藏全部
                        </Button>
                    </Space>

                </div>
            </div>
        }else {
            if(playlist){
                const tags = [];
                playlist.tags.map(r => {
                    tags.push(
                        <span className="tagsitem">{r}</span>
                    )
                })
                return <div className="PlayList_withId">
                    <Avatar shape="square" size={190} src={playlist.coverImgUrl}></Avatar>
                    <div className="PlayList_detail">
                        <div className="title">
                            <Tag color="magenta">歌单</Tag>
                            <span className="t_text">{playlist.name}</span>
                        </div>
                        <div className="create_author">
                            <Space>
                                <Avatar size={25} src={playlist.creator.avatarUrl}></Avatar>
                                <span>{playlist.creator.signature}</span>
                                <span>{fitterYMRTime(playlist.createTime)} 创建</span>
                            </Space>
                        </div>
                        <div className="PlayButton_box">
                            <Space>
                                <div className="Play_box">
                                    <Button onClick={this.PlayAll} className="PlayAll" icon={<CaretRightOutlined />}>
                                        播放全部
                                    </Button>
                                    <Button className="Add" icon={<PlusOutlined />}></Button>
                                </div>
                                <Button className="SCbut" icon={<FolderAddOutlined />}>
                                    收藏全部({playlist.trackCount})
                                </Button>
                            </Space>
                        </div>

                        <ul className="PlayId_det">
                            <li>标签:&nbsp; {tags}</li>
                            <li>歌曲:&nbsp; {playlist.trackCount} &nbsp;&nbsp;&nbsp;  播放: {this.CompCount(playlist.playCount)} </li>
                            <li>简介:&nbsp; {playlist.description} </li>
                        </ul>

                    </div>
                </div>
            }else {

            }

        }
    }

    CompCount(value){
        if(parseInt(value) > 10000){
            return parseInt(value/10000) + '万'
        }else {
            return value
        }
    }

    fitterSinger = (artists) => {
        let artistlsit = []
        artists.map((item,index) => {
            artistlsit.push(
                <span artistid={item.id} className="artistitem">
                    { item.name }
                </span>
            )
        })
        return <div className="artistlsit">{ artistlsit }</div>
    }

    fitterTime = (value) => {
        var theTime = parseInt(value/1000);// 秒
        var middle= 0;// 分
        var hour= 0;// 小时

        if(theTime > 60) {
            middle= parseInt(theTime/60);
            theTime = parseInt(theTime%60);
            if(middle> 60) {
                hour= parseInt(middle/60);
                middle= parseInt(middle%60);
            }
        }
        let Time = parseInt(theTime).toString().padStart(2, '0')
        let Middle = parseInt(middle).toString().padStart(2, '0')
        let Hour = parseInt(theTime).toString().padStart(2, '0')
        var result = "00:"+Time;
        if(middle > 0) {
            result = Middle+":"+Time;
        }
        if(hour> 0) {
            result = Hour + ":" + Middle+":"+Time;
        }
        return result;
    }

    isfav(item){
        return <HeartOutlined className="download_icon"/>
    }

    PlayThisSong(event,record){
        emitter.emit('PlayAudio',record.id,record);
    }

    render() {
        const { recommendList } = this.state;
        const columns = [
            {
                title: '',
                key: 'index',
                render: (text,record,index) => <div className="Index_Playindex">
                    <Space>
                        <span className="table_dt">{`${index+1}`.padStart(2,0)}</span>
                        {this.isfav(record)}
                        <VerticalAlignBottomOutlined className="download_icon" />
                    </Space>
                </div>
            },
            {
                title: '音乐标题',
                dataIndex: 'name',
                key: 'name',
                width: 300,
                render: text => <span className="table_name">{text}</span>
            },
            {
                title: '歌手',
                dataIndex: 'ar',
                key: 'ar',
                render: text => <div>
                    {this.fitterSinger(text)}
                </div>,
            },
            {
                title: '专辑',
                dataIndex: 'al',
                key: 'al',
                width: 240,
                render: text => <div albumid={text.id} className="album">{text.name}</div>,
            },
            {
                title: '时长',
                dataIndex: 'dt',
                key: 'dt',
                render: text => <span className="table_dt">{this.fitterTime(text)}</span>,
            },
        ];



        return(

            <div className="playlistPafe">
                <div className="playlistDet">
                    {this.PlayTitle()}
                </div>
                <div className="playlist_list"></div>
                <Divider style={{margin:"24px 0 0 0"}} />
                <Table className="Playlist_table" onRow={record => {
                    return {
                        onClick: event => {}, // 点击行
                        onDoubleClick: (event) => this.PlayThisSong(event,record),
                    };
                }} columns={columns} dataSource={recommendList} pagination={false} />
            </div>
        )
    }
}


export default connect(mapStateToProps,mapDispatchToProps)(withRouter(PlayListPage));